import { EggAppConfig, EggAppInfo, PowerPartial } from "egg";

export default (appInfo: EggAppInfo) => {
  const config = {} as PowerPartial<EggAppConfig>;

  // override config from framework / plugin
  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + "_1551702248007_1799";

  // add your egg config in here
  config.middleware = [];

  //配置egg-socket.io
  config.io = {
    init: {},
    namespace: {
      "/": {
        connectionMiddleware: ["auth"],
        packetMiddleware: ["packet"]
      }
    }
  };

  //配置egg-redis
  config.redis = {
    clients: {
      pub: {
        port: 6379,
        host: "127.0.0.1",
        password: "",
        db: 0
      },
      sub: {
        port: 6379,
        host: "127.0.0.1",
        password: "",
        db: 0
      }
    }
  };

  //配置sequelize
  config.sequelize = {
    dialect: "mysql",
    host: "127.0.0.1",
    username: "root",
    password: "chenbailin",
    port: 3306,
    database: "wechat_db",
    pool: {
      max: 100,
      min: 10
    }
  };

  config.onerror = {
    json: (err, ctx) => {
      let result: any;
      try {
        result = JSON.parse(err.message);
      } catch (e) {
        result = err.message;
      }
      if (result.code) {
        ctx.body = result;
      } else {
        ctx.body = { code: 3, msg: result };
      }
      ctx.status = 200;
    },
    html: (err, ctx) => {
      let result: any;
      try {
        result = JSON.parse(err.message);
      } catch (e) {
        result = err.message;
      }
      if (result.code) {
        ctx.body = JSON.stringify(result);
      } else {
        ctx.body = JSON.stringify({ code: 3, msg: result });
      }
      ctx.status = 200;
    }
  };

  config.cors = {
    origin:'*',
    allowMethods:'GET,POST,PUT,DELETE,OPTIONS'
  };

  config.security={
    domainWhiteList: [ 'http://127.0.0.1:7001' ],
    csrf:false
  }

  // add your special config in here
  const bizConfig = {
    sourceUrl: `https://github.com/eggjs/examples/tree/master/${appInfo.name}`
  };

  // the return config will combines to EggAppConfig
  return {
    ...config,
    ...bizConfig
  };
};
